package com.example.demo.tool.archery;

import cn.hutool.json.JSONObject;
import lombok.RequiredArgsConstructor;

import lombok.extern.slf4j.Slf4j;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;

/**
 * @author jiangjinwu
 * @version 1.0
 * @since 2025/10/24 17:09
 */

@Slf4j

public class ArcheryExecutor {

//    public static void main(String[] args) {
//        ArcheryQueryService queryService = new ArcheryQueryService();
//         QueryContext queryContext =  new QueryContext();
//        queryContext.setSelContent("select * from t_agency_relation where  1=1");
//        queryContext.setPageIndex(0);
//        queryContext.setPageSize(5000);
//        queryContext.setCookie("__bid_n=193d790be6a7184a73e539; _ga_YFKNQX5E65=GS1.1.1736917810.15.0.1736917819.0.0.0; _ga=GA1.2.2107992107.1721119513; csrftoken=AoaHusr5ONfkfEqho8SEwBWKIlLlzLgJPP2sm6XOzstzHF6WsLMBQ6CRhxtmSFX4; sessionid=a18jv7fp2pepwfga42ekczgzq81hkbj7");
//        queryContext.setCsrfToken("AoaHusr5ONfkfEqho8SEwBWKIlLlzLgJPP2sm6XOzstzHF6WsLMBQ6CRhxtmSFX4");
//        queryContext.setDynamicCondition("and parent_id = 24190");
//        JSONObject result = queryService.execute(queryContext);
//
//        NestResultContainer nestResultContainer = new NestResultContainer(result,"id","parent_id");
//        nestResultContainer.process(result);
//        while (nestResultContainer.hasNext()){
//            queryContext.setDynamicCondition(nestResultContainer.getDynamicCondition());
//            result = queryService.execute(queryContext);
//            nestResultContainer.process(result);
//        }
//        logger.info("deepth:{}",nestResultContainer.getDeepth());
//        logger.info("getSqlResult:{}",nestResultContainer.getSqlResult());
//        logger.info("result:{}",nestResultContainer.getData());
//    }

    public static void main(String[] args) {
        String storeParam = "101349887";
        String store = "select * from store where id in("+storeParam+")";
        String cloudStore = "select * from t_cloud_store where   cs_no in("+storeParam+")";
        //executeCloudStore(cloudStore, "t_cloud_store","all12");

        QueryContext queryContext = new QueryContext(ArcheryUrlEnum.JBZ_ARCHERY_URL);
        queryContext.setCookie("__bid_n=193d790be6a7184a73e539; _ga_YFKNQX5E65=GS1.1.1736917810.15.0.1736917819.0.0.0; _ga=GA1.2.2107992107.1721119513; csrftoken=bQZkwwHT0YfPgMPfgSM6zI1f4KdEkCLHLqboa8e4c5VDcbCcD2LhagVhHmjyQVRu; sessionid=35g99difntih15kw9dcllc5jmrjeoewt");
        queryContext.setCsrfToken("bQZkwwHT0YfPgMPfgSM6zI1f4KdEkCLHLqboa8e4c5VDcbCcD2LhagVhHmjyQVRu");
        queryContext.setSelContent( store);



//
//        String messageSql = "select * from t_message where  code ='STORE_SALES' and  markers ='S20251027202653793051777'";
//        executeMessage(messageSql,"t_message","1");
        queryContext.setSelContent( "select  * from t_agency_relation where  1=1 ");
        //queryContext.setDynamicCondition("and id in(28267)");
        //executeRewardDynamic(queryContext,"parent_id","id","t_agency_relation","123");


        queryContext.setPageIndex(0);
        queryContext.setPageSize(5000);
        queryContext.setInstanceName("服务商-测试-new");
        queryContext.setDbName("test-dev-reward");

        executeRewardSimple(queryContext,"t_reward_stats_period","123");

        List<String> tablesName = Arrays.asList("t_account_details");
        executeAll(tablesName,queryContext,"1");

    }

    private static void executeCloudStore(QueryContext queryContext, String tableName,String tenantId) {
        ArcheryQueryService queryService = new ArcheryQueryService();
        queryContext.setInstanceName("老生产绩效主库");
        queryContext.setDbName("store");


        queryContext.setPageIndex(0);
        queryContext.setPageSize(5000);

        queryContext.setDynamicCondition("");
        JSONObject result = queryService.execute(queryContext);
        SqlResultContainer nestResultContainer = new SqlResultContainer(result, "insert", tableName);
        nestResultContainer.process(result);


        String sqlResult = nestResultContainer.getSqlResult();
        logger.info("getSqlResult:{}", sqlResult);

        writeToFile(tableName, tenantId, true, sqlResult);
    }

    private static void writeToFile(String tableName, String tenantId, boolean append, String sqlResult) {
        var filePath = tableName + tenantId + ".sql";

        try (OutputStreamWriter writer = new OutputStreamWriter(
                new FileOutputStream(filePath, append), StandardCharsets.UTF_8)) {
            writer.write(sqlResult);
        } catch (
            IOException e) {
            throw new RuntimeException("生成 SQL 文件失败", e);
        }

    }


    public static void executeStore( QueryContext queryContext ,String tenantId) {

        executeCloudStore(queryContext, "store",tenantId);
    }


    private static void executeRewardSimple(QueryContext queryContext, String tableName,String tenantId) {

        queryContext.setDynamicCondition("");
        executeSimple(queryContext,tableName,tenantId);
    }


    static void  executeRewardDynamic(QueryContext queryContext, String idColumn,String parentColumn ,String tableName,String tenantId){
        ArcheryQueryService queryService = new ArcheryQueryService();
        queryContext.setPageIndex(0);
        queryContext.setPageSize(5000);
        queryContext.setInstanceName("服务商-生产-new");
        queryContext.setDbName("reward");
        JSONObject result = queryService.execute(queryContext);

        NestResultContainer nestResultContainer = new NestResultContainer(result,"t_agency_relation",idColumn,parentColumn);
        nestResultContainer.process(result);
        while (nestResultContainer.hasNext()){
            queryContext.setDynamicCondition(nestResultContainer.getDynamicCondition());
            result = queryService.execute(queryContext);
            nestResultContainer.process(result);
        }
        logger.info("deepth:{}",nestResultContainer.getDeepth());
        String sqlResult = nestResultContainer.getInsertSqlResult();
        logger.info("getSqlResult:{}",nestResultContainer.getSqlResult());
        logger.info("result:{}",nestResultContainer.getData());
        writeToFile(tableName, tenantId, true, sqlResult);
    }


    private static void executeMTSimple(QueryContext queryContext, String tableName,String tenantId) {
        queryContext.setInstanceName("服务商-reward");
        queryContext.setDbName("reward");
        queryContext.setDynamicCondition("");
        executeSimple(queryContext,tableName,tenantId);

    }

    private static void executeSimple(QueryContext queryContext, String tableName,String tenantId) {
        ArcheryQueryService queryService = new ArcheryQueryService();


        JSONObject result = null;
        SqlResultContainer nestResultContainer = null;
        String sqlResult = "";
        logger.info("getSqlResult:{}", sqlResult);
        boolean append = false;
        boolean hasNext = false;
        do{
            result = queryService.execute(queryContext);
            nestResultContainer = new SqlResultContainer(result, "insert", tableName);
            nestResultContainer.process(result);
            sqlResult = nestResultContainer.getSqlResult();
            if(queryContext.getPageSize()>0){
                append = true;
            }
            hasNext = nestResultContainer.getData().size()>=queryContext.getPageSize();
            writeToFile(tableName+"-"+tenantId+"-"+queryContext.getPageIndex(), tenantId, append, sqlResult);
            queryContext.setPageIndex(queryContext.getPageIndex()+1);
        } while(hasNext);
    }

    public static void executeAll(List<String> tableNames,QueryContext queryContext,String tenantId){
        tableNames.forEach(tableName->{
            String sql = "select * from "+tableName+" where tenant_id ="+tenantId;
            queryContext.setSelContent(sql);
            queryContext.setPageIndex(0);
            executeRewardSimple(queryContext,tableName,tenantId);
        });

    }
}
